package com.unionfetch.content_home.ui.account

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.transition.TransitionManager
import android.view.View
import android.view.ViewTreeObserver
import android.widget.Button
import android.widget.LinearLayout
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.unionfetch.content_home.R
import com.unionfetch.content_home.bean.UserStatus
import com.unionfetch.content_home.bean.UserType
import com.unionfetch.content_home.ui.OpenAccountGuideUtil
import com.unionftech.common.R.color
import com.unionftech.common.R.drawable
import com.unionftech.common.R.string
import com.unionftech.common.base.BaseActivity
import com.unionftech.common.base.BaseFragment
import com.unionftech.common.base.IUpdate
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.common.common.adapter.CommonFragmentStateAdapter
import com.unionftech.common.common.bean.KYCFileInfo
import com.unionftech.common.common.bean.SystemUserInfo
import com.unionftech.common.common.bean.UserKYCFileInfo
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.utils.ToastUtils
import com.unionftech.common.utils.serializable

class AccountManagerActivity : BaseActivity(), IUpdate {
    private val mBtnAddDemoAccount by lazy { findViewById<Button>(R.id.btn_add_demo_account) }
    private val mBtnAddLiveAccount by lazy { findViewById<Button>(R.id.btn_add_live_account) }
    private val mViewPager by lazy { findViewById<ViewPager2>(R.id.view_pager) }
    private val mTabLayout by lazy { findViewById<TabLayout>(R.id.tab_layout) }
    private lateinit var mFragments: List<BaseFragment>
    private lateinit var mTitles: List<String>
    private lateinit var mAdapter: CommonFragmentStateAdapter
    private lateinit var mDemoAccountListFragment: DemoAccountListFragment
    private lateinit var mLiveAccountListFragment: LiveAccountListFragment
    private var mInitIndex = 0
    private var mObserver: ViewTreeObserver.OnGlobalLayoutListener? = null
    private var mKycFileInfo: UserKYCFileInfo? = null

    companion object {

        private const val TAG = "AccountManagerActivity"

        private const val PARAMS_INIT_INDEX = "params_init_index"
        private const val PARAMS_KYC_FILE_INFO = "params_kyc_file_info"

        @JvmStatic
        fun startThis(context: Context, initIndex: Int, kycFileInfo: UserKYCFileInfo?) {
            Intent(context, AccountManagerActivity::class.java).apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                putExtra(PARAMS_INIT_INDEX, initIndex)
                putExtra(PARAMS_KYC_FILE_INFO, kycFileInfo)
                context.startActivity(this)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun obtainIntentData(intent: Intent) {
        super.obtainIntentData(intent)
        mInitIndex = intent.getIntExtra(PARAMS_INIT_INDEX, 0)
        mKycFileInfo = intent.serializable(PARAMS_KYC_FILE_INFO)
    }

    override fun initLayout() = R.layout.activity_account_manager

    override fun initLanguageText() {
        super.initLanguageText()
        mBtnAddDemoAccount.text = DynamicResourceManager.getString(string.add_demo_account)
        mBtnAddLiveAccount.text = DynamicResourceManager.getString(string.add_live_account)
    }

    override fun initData() {
        super.initData()
        mTitles = listOf(
            DynamicResourceManager.getString(mContext, string.live_account),
            DynamicResourceManager.getString(mContext, string.demo_account)
        )
        mDemoAccountListFragment = DemoAccountListFragment.newInstance()
        mLiveAccountListFragment = LiveAccountListFragment.newInstance(mKycFileInfo)
        mFragments = listOf(mLiveAccountListFragment, mDemoAccountListFragment)
        mAdapter = CommonFragmentStateAdapter(mActivity)
        mAdapter.addFragment(mFragments)
    }

    override fun setListener() {
        super.setListener()
        GlobalInfoManager.getInstance().addListener(this)
        mLiveAccountListFragment.setCallBack { show: Boolean ->
            // 开始过渡动画
            TransitionManager.beginDelayedTransition(mRootView)
            if (show) {
                mBtnAddLiveAccount.visibility = View.VISIBLE
            } else {
                mBtnAddLiveAccount.visibility = View.GONE
            }
            GlobalInfoManager.getInstance().getSystemUserInfo()?.also { userInfo ->
                //若不是IB主账号审核不通过，“新增真实账户”按钮消失
                val isIB = userInfo.type == UserType.IB.type
                val isFailed = userInfo.status == UserStatus.USER_FAILURE.status
                if (!isIB && isFailed) {
                    mBtnAddLiveAccount.visibility = View.GONE
                }
            }
        }
        mDemoAccountListFragment.setCallBack { show: Boolean ->
            // 开始过渡动画
            TransitionManager.beginDelayedTransition(mRootView)
            if (show) {
                mBtnAddDemoAccount.visibility = View.VISIBLE
            } else {
                mBtnAddDemoAccount.visibility = View.GONE
            }
        }
        mObserver = ViewTreeObserver.OnGlobalLayoutListener {
            mViewPager.viewTreeObserver.removeOnGlobalLayoutListener(mObserver)
            mViewPager.setCurrentItem(mInitIndex, false)
        }
        mViewPager.viewTreeObserver.addOnGlobalLayoutListener(mObserver)
        mBtnAddDemoAccount.setOnClickListener(this)
        mBtnAddLiveAccount.setOnClickListener(this)
    }

    override fun setView() {
        super.setView()
        initTitleBar()
        setupViewpager()
    }

    private fun initTitleBar() {
        hideCenterTitle()
        setBackText(
            DynamicResourceManager.getString(string.account_manager_title), mContext.getColor(
                color.color_1C1D21
            )
        )
    }

    private fun setupViewpager() {
        mViewPager.adapter = mAdapter
        mViewPager.offscreenPageLimit = 1
        mViewPager.isSaveEnabled = false
        TabLayoutMediator(mTabLayout, mViewPager) { tab, position ->
            tab.text = mTitles[position]
        }.attach()
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.btn_add_live_account -> {
                checkLiveGotoAdd()
            }

            R.id.btn_add_demo_account -> {
                AddDemoTradeAccountActivity.startThis(mContext)
            }
        }
    }

    private fun checkLiveGotoAdd() {
        GlobalInfoManager.getInstance().getSystemUserInfo()?.also { info ->
            val isIB = info.type == UserType.IB.type
            if (isIB) {
                checkLiveGotoAddByIB(info)
            } else {
                checkLiveGotoAddByRC(info)
            }
        }
    }

    private fun checkLiveGotoAddByIB(info: SystemUserInfo) {
        //4.审核中
        if (!info.hasAccount && !info.hasAudit && info.hasAuditMain == -1) {
            //立即开户
            OpenAccountGuideUtil.gotoOpenAccountStep()
            finish()
            return
        }
        if (!info.hasAccount && info.hasAudit) {
            //没有交易账号,有在审核中的交易账号(审核中)
            //审核中
            ToastUtils.longToast(DynamicResourceManager.getString(string.open_account_waiting_tip))
            return
        }
        if (info.status == UserStatus.USER_FAILURE.status) {
            //审核失败
            //ib: 没有审核失败的状态, 审核失败走立即开户的逻辑
            OpenAccountGuideUtil.gotoOpenAccountStep()
            finish()
            return
        }
        //跳转添加同名账户
        AddLiveTradeAccountActivity.startThis(mContext)
    }

    private fun checkLiveGotoAddByRC(info: SystemUserInfo) {
        //RC
        if (info.status < UserStatus.USER_WAITTING.status) {
            //1.开户步骤没有完成
            OpenAccountGuideUtil.gotoOpenAccountStep()
            finish()
            return
        }
        //2.身份证明没完成
        if (TextUtils.isEmpty(info.filesStatus) || info.filesStatus == "00") {
            //POI和POA都没有填写
            OpenAccountGuideUtil.gotoPoiAuth(
                isSupplement = true, isContinuePoa = true
            )
            return
        }
        if (info.filesStatus == "10") {
            //上传地址证明
            OpenAccountGuideUtil.gotoPoaAuth(isSupplement = false)
            return
        }
        //3.身份证明和地址证明都完成上传，判断补料状态
        if (info.filesStatus == "11") {
            mKycFileInfo?.also { kycInfo ->
                if (kycInfo.enable) {
                    when (kycInfo.supplementTypes) {
                        "1" -> {
                            //补料身份证明
                            OpenAccountGuideUtil.gotoPoiAuth(
                                isSupplement = true, isContinuePoa = false
                            )
                            return
                        }

                        "2" -> {
                            //补料地址证明
                            OpenAccountGuideUtil.gotoPoaAuth(isSupplement = true)
                            return
                        }

                        "1,2" -> {
                            //补充身份证明和地址证明
                            //如果poi上传完成，则变成上传poa
                            OpenAccountGuideUtil.gotoPoiAuth(
                                isSupplement = true, isContinuePoa = true
                            )
                            return
                        }
                    }
                }
            }
        }
        //4.审核中
        if (info.status == UserStatus.USER_WAITTING.status) {
            ToastUtils.longToast(DynamicResourceManager.getString(string.open_account_waiting_tip))
            return
        }
        //5.未审核的交易账户不能添加同名账号
        if (mLiveAccountListFragment.getHaveAuditMainAccount()) {
            ToastUtils.longToast(DynamicResourceManager.getString(string.have_audit_account_cannt_add))
            return
        }
        //跳转添加同名账户
        AddLiveTradeAccountActivity.startThis(mContext)
    }

    override fun onUpdate(obj: Any?) {
        if (obj is Int) {
            mViewPager.post {
                if (obj == GlobalInfoManager.UPDATE_DEMO_LIST) {
                    mViewPager.currentItem = 1
                } else if (obj == GlobalInfoManager.UPDATE_LIVE_LIST) {
                    mViewPager.currentItem = 0
                } else if (obj == GlobalInfoManager.FINISH_SELF) {
                    finish()
                }
            }
        }
    }

    override fun onDestroy() {
        GlobalInfoManager.getInstance().remove(this)
        super.onDestroy()
    }
}